package com.ruoyi.web.controller.gcgl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gcgl.domain.GcProject;
import com.ruoyi.gcgl.domain.GcProjectFlow;
import com.ruoyi.gcgl.domain.GcProjectYbfy;
import com.ruoyi.gcgl.domain.GcSupply;
import com.ruoyi.gcgl.service.IGcProjectFlowService;
import com.ruoyi.gcgl.service.IGcProjectService;
import com.ruoyi.gcgl.service.IGcProjectYbfyService;
import com.ruoyi.gcgl.service.IGcSupplyService;

/**
 * 一般性费用Controller
 * 
 * @author ruoyi
 * @date 2022-11-29
 */
@Controller
@RequestMapping("/gcgl/ybfy")
public class GcProjectYbfyController extends BaseController{
	
	private static final Logger log = LoggerFactory.getLogger(GcProjectYbfyController.class);
	
    private String prefix = "gcgl/ybfy";

    @Autowired
    private IGcProjectYbfyService gcProjectYbfyService;
    @Autowired
    private IGcProjectService gcProjectService;
    @Autowired
    private IGcProjectFlowService gcProjectFlowService;
    @Autowired
    private IGcSupplyService gcSupplyService;
    @Autowired
    private ServerConfig serverConfig;
    
    private static final String FILE_DELIMETER = ",";

    @RequiresPermissions("gcgl:ybfy:view")
    @GetMapping()
    public String ybfy()
    {
        return prefix + "/ybfy";
    }

    /**
     * 查询一般性费用列表
     */
    @RequiresPermissions("gcgl:ybfy:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GcProjectYbfy gcProjectYbfy)
    {
        startPage();
        gcProjectYbfy.setDeleteFlag(1);
        if(getSysUser().isShow43R(getUserId())){
        gcProjectYbfy.setCreateUser(getLoginName());
        }
        List<GcProjectYbfy> list = gcProjectYbfyService.selectGcProjectYbfyList(gcProjectYbfy);
        return getDataTable(list);
    }

    /**
     * 导出一般性费用列表
     */
    @RequiresPermissions("gcgl:ybfy:export")
    @Log(title = "一般性费用", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GcProjectYbfy gcProjectYbfy)
    {
    	gcProjectYbfy.setDeleteFlag(1);
        if(getSysUser().isShow()){
        gcProjectYbfy.setCreateUser(getLoginName());
        }
        List<GcProjectYbfy> list = gcProjectYbfyService.selectGcProjectYbfyList(gcProjectYbfy);
        ExcelUtil<GcProjectYbfy> util = new ExcelUtil<GcProjectYbfy>(GcProjectYbfy.class);
        return util.exportExcel(list, "一般性费用数据");
    }

    /**
     * 新增一般性费用
     */
    @GetMapping("/add/{gcProjectid}")
    public String add(ModelMap mmap,@PathVariable("gcProjectid") Long gcProjectid){
    	GcProject gcProject = gcProjectService.selectGcProjectById(gcProjectid);
    	mmap.put("gcProject", gcProject);
    	
    	GcSupply gcSupply = new GcSupply();
    	gcSupply.setDeleteFlag(1);
    	gcSupply.setType(4);
    	List<GcSupply> gcSupplyLis = gcSupplyService.selectGcSupplyList(gcSupply);
    	mmap.put("gcSupplyLis", gcSupplyLis);
        return prefix + "/add";
    }

    /**
     * 新增保存一般性费用
     */
    @RequiresPermissions("gcgl:ybfy:add")
    @Log(title = "一般性费用", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public synchronized AjaxResult addSave(GcProjectYbfy gcProjectYbfy){
    	
    	try{
//            SimpleDateFormat sdy = new SimpleDateFormat("yyyy");
//    		SimpleDateFormat sdm = new SimpleDateFormat("MM");
//    		int year = Integer.parseInt(sdy.format(new Date()));
//    		int month = Integer.parseInt(sdm.format(new Date()));
//    		GcProjectYbfy newObj = new GcProjectYbfy();
//    		newObj.setDeleteFlag(1);
//    		newObj.setCreateAt(DateUtils.getFisrtDayOfMonth(year, month));
//    		newObj.setUpdateAt(DateUtils.getLastDayOfMonth(year, month));
//    		List<GcProjectYbfy> lisCount = gcProjectYbfyService.selectGcProjectYbfyList(newObj);
//    		String no = String.format("%02d", lisCount.size()+1);
//    		gcProjectYbfy.setOrderNo(year+"-"+no);
    		
    		GcProject gcProject = gcProjectService.selectGcProjectById(gcProjectYbfy.getGcProjectid());
    		gcProjectYbfy.setOrderNo(gcProject.getOrderNo());
    		
    		GcSupply supplyObj = gcSupplyService.selectGcSupplyById(gcProjectYbfy.getSupplyId());
    		gcProjectYbfy.setSupplyName(supplyObj.getName());
            gcProjectYbfy.setDeleteFlag(1);
            gcProjectYbfy.setCreateAt(new Date());
            gcProjectYbfy.setUpdateAt(new Date());
            gcProjectYbfy.setCreateUser(getLoginName());
            gcProjectYbfy.setUpdateUser(getLoginName());
            gcProjectYbfy.setStatus(0);
            gcProjectYbfyService.insertGcProjectYbfy(gcProjectYbfy);
            
            //查询流程图
            GcProjectFlow gcProjectFlow = new GcProjectFlow();
            gcProjectFlow.setGcProjectid(gcProjectYbfy.getGcProjectid());
            gcProjectFlow = gcProjectFlowService.selectGcProjectFlowList(gcProjectFlow).get(0);
            
            GcProjectFlow obj = new GcProjectFlow();
            //判断是否启用项目审批节点
            obj.setYbxfy(1);
            obj.setYbxfyfp(0);
            obj.setYbxfyfk(0);
            obj.setGcProjectid(gcProjectFlow.getGcProjectid());
            gcProjectFlowService.updateGcProjectFlow(obj);
        }
        catch (Exception e){
            log.error("上传文件！", e);
            return error(e.getMessage());
        }
    	
        return toAjax(1);
    }

    /**
     * 修改一般性费用
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        GcProjectYbfy obj = gcProjectYbfyService.selectGcProjectYbfyById(id);
        if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
        	String[] zlis = obj.getZlwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += RuoYiConfig.getOnPath()+zlis[i]+",";
        	}
        	obj.setZlwj(file);
        }
        mmap.put("gcProjectYbfy", obj);
        
        GcSupply gcSupply = new GcSupply();
    	gcSupply.setDeleteFlag(1);
    	gcSupply.setType(4);
    	List<GcSupply> gcSupplyLis = gcSupplyService.selectGcSupplyList(gcSupply);
    	mmap.put("gcSupplyLis", gcSupplyLis);
        return prefix + "/edit";
    }

    /**
     * 修改保存一般性费用
     */
    @Log(title = "一般性费用", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GcProjectYbfy gcProjectYbfy)
    {
    	try{
    		GcSupply supplyObj = gcSupplyService.selectGcSupplyById(gcProjectYbfy.getSupplyId());
    		gcProjectYbfy.setSupplyName(supplyObj.getName());
    		
    		gcProjectYbfy.setStatus(0);
    		gcProjectYbfy.setUpdateAt(new Date());
            gcProjectYbfy.setUpdateUser(getLoginName());
            gcProjectYbfyService.updateGcProjectYbfy(gcProjectYbfy);
        }
        catch (Exception e){
            log.error("上传文件！", e);
            return error(e.getMessage());
        }
    	
        return toAjax(1);
    }

    /**
     * 删除一般性费用
     */
    @RequiresPermissions("gcgl:ybfy:remove")
    @Log(title = "一般性费用", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(gcProjectYbfyService.deleteGcProjectYbfyByIds(ids));
    }
    
    //项目评审
    @RequiresPermissions("gcgl:ybfy:psview")
    @GetMapping("/ps")
    public String ybfyps(){
        return prefix + "/ybfyps";
    }
    
    /**
     * 查询一般性费用列表
     */
    @PostMapping("/pslist")
    @ResponseBody
    public TableDataInfo pslist(GcProjectYbfy gcProjectYbfy)
    {
        startPage();
        gcProjectYbfy.setDeleteFlag(1);
        gcProjectYbfy.setStatus(0);
        List<GcProjectYbfy> list = gcProjectYbfyService.selectGcProjectYbfyList(gcProjectYbfy);
        return getDataTable(list);
    }
    
    @Log(title = "通过", businessType = BusinessType.UPDATE)
    @PostMapping("/yes")
    @ResponseBody
    public AjaxResult yes(String ids, ModelMap mmap){
    	String[] id = Convert.toStrArray(ids);
    	for(int i=0;i<id.length;i++){
    		GcProjectYbfy ybfy = gcProjectYbfyService.selectGcProjectYbfyById(Long.parseLong(id[i].toString()));
    		if(ybfy!=null){
    			GcProjectYbfy gcProjectYbfy = new GcProjectYbfy();
        		gcProjectYbfy.setId(Long.parseLong(id[i]));
        		gcProjectYbfy.setStatus(1);
        		gcProjectYbfy.setSpr(getLoginName());
        		gcProjectYbfy.setSprAt(new Date());
        		gcProjectYbfyService.updateGcProjectYbfy(gcProjectYbfy);
    		}
    		
    	}
    	
    	return toAjax(1);
    }
    
    @Log(title = "不通过", businessType = BusinessType.UPDATE)
    @PostMapping("/no")
    @ResponseBody
    public AjaxResult no(String ids, ModelMap mmap){
    	String[] id = Convert.toStrArray(ids);
    	for(int i=0;i<id.length;i++){
    		GcProjectYbfy ybfy = gcProjectYbfyService.selectGcProjectYbfyById(Long.parseLong(id[i].toString()));
    		if(ybfy!=null){
    			GcProjectYbfy gcProjectYbfy = new GcProjectYbfy();
        		gcProjectYbfy.setId(Long.parseLong(id[i]));
        		gcProjectYbfy.setStatus(2);
        		gcProjectYbfy.setSpr(getLoginName());
        		gcProjectYbfy.setSprAt(new Date());
            	gcProjectYbfyService.updateGcProjectYbfy(gcProjectYbfy);
            	
            	GcProjectFlow gcProjectFlow = new GcProjectFlow();
            	gcProjectFlow.setGcProjectid(ybfy.getGcProjectid());
            	gcProjectFlow.setYbxfy(0);
            	gcProjectFlow.setUpdateAt(new Date());
            	gcProjectFlow.setUpdateUser(getLoginName());
            	gcProjectFlowService.updateGcProjectFlow(gcProjectFlow);
    		}
    		
    	}
    	return toAjax(1);
    }
    
    /**
     * 总经理项目评审
     * @return
     */
    @RequiresPermissions("gcgl:ybfy:zjlpsview")
    @GetMapping("/zjlps")
    public String zjlps(){
        return prefix + "/ybfyzjlps";
    }
    
    /**
     * 查询一般性费用列表
     */
    @PostMapping("/zjlpslist")
    @ResponseBody
    public TableDataInfo zjlpslist(GcProjectYbfy gcProjectYbfy)
    {
        startPage();
        gcProjectYbfy.setDeleteFlag(1);
        gcProjectYbfy.setStatus(1);
        List<GcProjectYbfy> list = gcProjectYbfyService.selectGcProjectYbfyList(gcProjectYbfy);
        return getDataTable(list);
    }
    
    @Log(title = "通过", businessType = BusinessType.UPDATE)
    @PostMapping("/zjlyes")
    @ResponseBody
    public AjaxResult zjlyes(String ids, ModelMap mmap){
    	String[] id = Convert.toStrArray(ids);
    	for(int i=0;i<id.length;i++){
    		GcProjectYbfy ybfy = gcProjectYbfyService.selectGcProjectYbfyById(Long.parseLong(id[i].toString()));
    		if(ybfy!=null){
    			GcProjectYbfy gcProjectYbfy = new GcProjectYbfy();
        		gcProjectYbfy.setId(Long.parseLong(id[i]));
        		gcProjectYbfy.setStatus(3);
        		gcProjectYbfy.setZjl(getLoginName());
        		gcProjectYbfy.setZjlAt(new Date());
        		gcProjectYbfyService.updateGcProjectYbfy(gcProjectYbfy);
            	
            	GcProjectFlow gcProjectFlow = new GcProjectFlow();
            	gcProjectFlow.setGcProjectid(ybfy.getGcProjectid());
            	gcProjectFlow.setYbxfy(1);
            	gcProjectFlow.setYbxfyfk(0);
            	gcProjectFlow.setYbxfyfp(1);
            	gcProjectFlow.setUpdateAt(new Date());
            	gcProjectFlow.setUpdateUser(getLoginName());
            	gcProjectFlowService.updateGcProjectFlow(gcProjectFlow);
    		}
    		
    	}
    	
    	return toAjax(1);
    }
    
    @Log(title = "不通过", businessType = BusinessType.UPDATE)
    @PostMapping("/zjlno")
    @ResponseBody
    public AjaxResult zjlno(String ids, ModelMap mmap){
    	String[] id = Convert.toStrArray(ids);
    	for(int i=0;i<id.length;i++){
    		GcProjectYbfy ybfy = gcProjectYbfyService.selectGcProjectYbfyById(Long.parseLong(id[i].toString()));
    		if(ybfy!=null){
    			GcProjectYbfy gcProjectYbfy = new GcProjectYbfy();
        		gcProjectYbfy.setId(Long.parseLong(id[i]));
        		gcProjectYbfy.setStatus(4);
        		gcProjectYbfy.setZjl(getLoginName());
        		gcProjectYbfy.setZjlAt(new Date());
            	gcProjectYbfyService.updateGcProjectYbfy(gcProjectYbfy);
            	
            	GcProjectFlow gcProjectFlow = new GcProjectFlow();
            	gcProjectFlow.setGcProjectid(ybfy.getGcProjectid());
            	gcProjectFlow.setYbxfy(0);
            	gcProjectFlow.setUpdateAt(new Date());
            	gcProjectFlow.setUpdateUser(getLoginName());
            	gcProjectFlowService.updateGcProjectFlow(gcProjectFlow);
    		}
    		
    	}
    	return toAjax(1);
    }
    
    @GetMapping("/detailgcsp/{id}")
    public String detailgcsp(@PathVariable("id") Long id, ModelMap mmap)
    {
        GcProjectYbfy obj = gcProjectYbfyService.selectGcProjectYbfyById(id);
        if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
        	String[] zlis = obj.getZlwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += RuoYiConfig.getOnPath()+zlis[i]+",";
        	}
        	obj.setZlwj(file);
        }
        mmap.put("gcProjectYbfy", obj);
        
        GcSupply gcSupply = new GcSupply();
    	gcSupply.setDeleteFlag(1);
    	gcSupply.setType(4);
    	List<GcSupply> gcSupplyLis = gcSupplyService.selectGcSupplyList(gcSupply);
    	mmap.put("gcSupplyLis", gcSupplyLis);
        return prefix + "/detailgcsp";
    }
    
    @GetMapping("/detailzjlsp/{id}")
    public String detailzjlsp(@PathVariable("id") Long id, ModelMap mmap)
    {
        GcProjectYbfy obj = gcProjectYbfyService.selectGcProjectYbfyById(id);
        if(obj.getZlwj()!=null && !obj.getZlwj().equals("")){
        	String[] zlis = obj.getZlwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += RuoYiConfig.getOnPath()+zlis[i]+",";
        	}
        	obj.setZlwj(file);
        }
        mmap.put("gcProjectYbfy", obj);
        
        GcSupply gcSupply = new GcSupply();
    	gcSupply.setDeleteFlag(1);
    	gcSupply.setType(4);
    	List<GcSupply> gcSupplyLis = gcSupplyService.selectGcSupplyList(gcSupply);
    	mmap.put("gcSupplyLis", gcSupplyLis);
        return prefix + "/detailzjlsp";
    }
    
    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception{
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}